package com.resataurant.Controller.User;

import com.resataurant.Entity.Dish;
import com.resataurant.Service.Impl.UserServiceImpl;
import com.resataurant.Service.UserService;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "BuyCartServlet",urlPatterns = "/BuyCartServlet")
public class BuyCartServlet extends HttpServlet {
    public UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");//防止中文乱码

        String dishid = request.getParameter("id");//获取用户账号
        String method = request.getParameter("method");
        HashMap<String, Dish> cart = (HashMap<String, Dish>) request.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new HashMap<>();
        }
        switch (method) {
            case "add":
                if (cart.containsKey(dishid)) {
                    Dish dish = cart.get(dishid).returnDish();
                    cart.put(dishid, dish);
                    request.getSession().setAttribute("cartres", "1");
                } else {
                    cart.put(dishid, userService.searchDishById(dishid).returnDish());
                    request.getSession().setAttribute("cartres", "1");
                }
                request.getSession().setAttribute("cart", cart);
                System.out.println("购物车内容:");
                for (Dish dish : cart.values()) {
                    System.out.println(dish.getDishName());
                    System.out.println(dish.getW_num());
                }
                response.sendRedirect("user.jsp");
                break;
            case "del":
                if (cart.containsKey(dishid))
                    cart.remove(dishid);
                request.getSession().setAttribute("cartDelres", "1");
                System.out.println("清除成功"+dishid);
                response.sendRedirect("BuyCart.jsp");
                break;

            case "delAll":
                cart.clear();
                request.getSession().setAttribute("cartDelAllres", "1");
                response.sendRedirect("BuyCart.jsp");
                break;
        }
    }
}